package com.virgo.mongo.dao;

import com.virgo.mongo.domain.CollectionIdDo;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

@Component
public class CollectionIdDao extends BaseMongoDao {

	/**
	 * 维护集合的主键id
	 * @param collectionName 集合名称
	 * @return id
	 */
	public Long getCollectionId(String collectionName){
		//查询条件
		Query query = new Query(Criteria.where("collectionName").is(collectionName));
		//要更新的数据
		Update update = new Update().inc("collectionId",1).set("collectionName",collectionName);
		FindAndModifyOptions options = new FindAndModifyOptions();
		// 先查询，如果没有符合条件的，会执行插入，插入的值是查询值 ＋ 更新值
		options.upsert(true);
		// 返回当前最新值
		options.returnNew(true);
		CollectionIdDo collectionIdDo = mongoTemplate.findAndModify(query,update,options, CollectionIdDo.class);
		if (null == collectionIdDo) {
			return 1L;
		}
		return collectionIdDo.getCollectionId();
	}

}
